#!/bin/bash
source /etc/profile
source ~/.bash_profile

if [ $# != 2 ] ; then
	echo "USAGE: sh $0 OneSQL_TAR_FILE TARGET_PATH"
	echo " e.g.: sh $0 OneSQL-1.1.0-c4ee475f-Linux-glibc2.28-aarch64.tar.xz /u01/onesql"
	exit 1;
fi

FILENAME=$(echo $1| awk -F '.' '{print $1"."$2"."$3"."$4}')
suffix=$(echo $1| awk -F '.' '{print $5"."$6}')

echo ${FILENAME}

# 二进制安装包名称
DB_TAR_FILE=$1

# 数据库安装目标位置
DB_WORK_DIR=$2

# 数据库软件安装位置
DB_BASE_DIR=${DB_WORK_DIR}/svr/onesql

# 数据库端口
DB_PORT="3306"

# 配置文件路径
DB_CNF_FILE="${DB_WORK_DIR}/conf/my.cnf"

# 数据库密码
DB_PASS=Test@1234

#当前目录
PWD_DIR=`pwd`

#初始化user脚本文件
DB_SQL=${PWD_DIR}/user.sql

# 数据库数据路径
DB_DATA_DIR="${DB_WORK_DIR}/data"
DB_TMP_DIR="${DB_WORK_DIR}/tmp"

# 日志文件、Socket文件、PID文件
DB_SOCKET="${DB_WORK_DIR}/socket/onesql.sock"
DB_GENERAL_LOG_FILE="${DB_WORK_DIR}/log/general.log"
DB_LOG_BIN="${DB_WORK_DIR}/binlog/binlog"
DB_RELAY_LOG="${DB_WORK_DIR}/log/relaylog"
DB_LOG_ERROR="${DB_WORK_DIR}/log/error.log"
DB_SLOW_QUERY_LOG_FILE="${DB_WORK_DIR}/log/slow_query_log.log"
DB_PID_FILE="${DB_WORK_DIR}/pid/mysqld.pid"

# 系统服务文件
DB_SERVICE_FILE_PATH="/usr/lib/systemd/system/onesql.service"

# ----------内部变量---------
# 数据库是否成功启动
DB_IS_START_SUCCESS=no

# 第0步：创建用户
function func_user() {
    echo "**********************************Creating user"
	groupadd onesql
	useradd -g onesql -s /bin/bash onesql
	echo "**********************************Current user"
	whoami
}

# 第1步：创建目录
function func_mkdir() {
    # 删除解压的数据库源代码
    echo "**********************************Deleteing  ${DB_DATA_DIR}"
    rm -rf ${DB_WORK_DIR}/*
	
    echo "**********************************Createing  ${DB_DATA_DIR}"
    mkdir -p ${DB_DATA_DIR}
    mkdir -p ${DB_WORK_DIR}/{binlog,conf,data,log,pid,sh,socket,sql,svr,tmp}
    func_uncompress
    cd ${DB_WORK_DIR}/svr
    ln -s ${FILENAME} onesql
    chown -R onesql:onesql ${DB_WORK_DIR}
}

# 第2步：解压缩
function func_uncompress() {
    # 解压缩数据库源码
	echo "**********************************Uncompress   ${DB_TAR_FILE}"
	rm -rf ${DB_WORK_DIR}/svr/*
	
	if [ "$suffix" == "tar.xz" ]; then

		echo "File $DB_TAR_FILE is  a xz file."
		tar xJf ${DB_TAR_FILE} -C ${DB_WORK_DIR}/svr
		
	elif [ "$suffix" == "tar.gz" ]; then
	
		echo "File $DB_TAR_FILE is a gz file."
		tar xzf ${DB_TAR_FILE} -C ${DB_WORK_DIR}/svr
		
		echo "File $DB_TAR_FILE unzip......................OK."
	else 
		echo "File $DB_TAR_FILE is not a compress file."
	fi
}

# 第3步：生成MySQL配置文件
function func_create_mysql_config() {
    echo "**********************************Create OneSQL Config Start"
    rm -rf ${DB_CNF_FILE}
    touch ${DB_CNF_FILE}
    echo "[mysqld]
basedir = ${DB_BASE_DIR}
datadir = ${DB_DATA_DIR}
user = onesql
port = ${DB_PORT}
socket = ${DB_SOCKET}

tmpdir = ${DB_TMP_DIR}
general_log_file = ${DB_GENERAL_LOG_FILE}
log_bin = ${DB_LOG_BIN}
relay_log = ${DB_RELAY_LOG}
slow_query_log_file = ${DB_SLOW_QUERY_LOG_FILE}
log_error = ${DB_LOG_ERROR}
pid_file = ${DB_PID_FILE}

binlog_ignore_db = dbscale_tmp
default_authentication_plugin = mysql_native_password
enforce_gtid_consistency = ON
gtid_mode = ON

innodb_dedicated_server = ON
lower_case_table_names = 1
innodb_flush_method = O_DIRECT_NO_FSYNC
innodb_flush_log_at_trx_commit = 1
innodb_log_files_in_group=2
log_timestamps=SYSTEM
slow_query_log = OFF
sort_buffer_size = 2M
ssl = OFF
skip_log_bin
[mysql]
socket = ${DB_SOCKET}

[client]
port = ${DB_PORT}
user=root
password=
socket = ${DB_SOCKET}
default-character-set=utf8" >> ${DB_CNF_FILE}
    
    echo "**********************************Create OneSQL Config Finished"
    chown -R onesql:onesql ${DB_CNF_FILE}
}

# 第4步：初始化数据库实例
# 这里默认使用root登录
function func_init_database() {
    echo "**********************************Initialize database"
    cd ${DB_BASE_DIR}/bin
    ./mysqld --defaults-file=${DB_CNF_FILE} --initialize-insecure
}


# 第5步：启动数据库实例
# 这里默认使用root登录
function func_start_database() {
    echo "**********************************Starting database"
    cd ${DB_BASE_DIR}/bin
    #./mysqld_safe --defaults-file=${DB_CNF_FILE} --user=root &
    ./mysqld --defaults-file=${DB_CNF_FILE} --daemonize --user=onesql
    
    #务必等待启动成功在执行后续
    echo "**********************************"
    echo "**********************************"
    echo "**********************************Started database"
}

# 可选步：停止数据库
function func_stop_database() {
	echo "**********************************Stopping database"
	#GREP_RESULT=`ps -ef | grep mysqld | grep -v grep`
	GREP_RESULT=`netstat -nlp | grep ${DB_PORT} | grep -v grep`
	
	# 如果存在已启动实例，则stop
	if [[ "${GREP_RESULT}" ]];then
		 ${DB_BASE_DIR}/bin/mysqladmin -uroot -P${DB_PORT} -p${DB_PASS} -S ${DB_SOCKET} shutdown
		echo "**********************************stop OK!"
	else
		echo "**********************************No instance to Stop!"
	fi
}

# 可选步：对数据库是否启动做基本的验证
function func_check_instance() {
    # 检查是否启动了mysql进程
	echo "**********************************Checking OneSQL process"
	echo "**********************************"
	ps -ef | grep mysqld | grep -v grep
	
	echo "**********************************Checking OneSQL listening port"
	echo "**********************************"
	netstat -nlp | grep onesql 
    GREP_RESULT=`ps -ef | grep mysqld | grep -v grep`
    #echo ${GREP_RESULT}
    # 判定结果是否为空
    if [[ "${GREP_RESULT}" ]];then
        DB_IS_START_SUCCESS="yes"
        echo "**********************************OneSQL instance already started! "
    else
        DB_IS_START_SUCCESS="no"
        echo "**********************************OneSQL instance not started..."
    fi
}

# 第6步：创建用户
function func_create_db_user() {
    cd ${DB_BASE_DIR}/bin
    ./mysql -h127.0.0.1 -uroot -P${DB_PORT} -e "show databases;" 
    ./mysql -h127.0.0.1 -uroot -P${DB_PORT}  < ${DB_SQL}
    ./mysql -h127.0.0.1 -uroot -P${DB_PORT} -p${DB_PASS} -e "select user,host from mysql.user;" 
    ./mysql -h127.0.0.1 -uroot -P${DB_PORT} -p${DB_PASS} -e "show databases;" 

}

# 第7步：设置环境变量
function func_set_env() {
    echo """
export ONESQL_PATH=$DB_BASE_DIR/bin
export PATH="\$PATH:\$ONESQL_PATH"
export TPCC=/opt/tpcc/benchmarksql5.0-mysql/run
export PATH="\$PATH:\$TPCC"
alias mlogin='$DB_BASE_DIR/bin/mysql -uroot -p -h127.0.0.1 '
alias mstop='$DB_BASE_DIR/bin/mysqladmin --defaults-file=$DB_CNF_FILE -uroot -p --socket=$DB_SOCKET shutdown'
alias mstart='$DB_BASE_DIR/bin/mysqld --defaults-file=$DB_CNF_FILE --user=mysql & '
    """ >> ~/.bash_profile
}

function func_create_systemd_file_and_restart() {
    echo "**********************************Create OneSQL Service Start"
    rm -rf ${DB_SERVICE_FILE_PATH}
    touch ${DB_SERVICE_FILE_PATH}
    echo "[Unit]
Description=OneSQL
After=network.target
After=syslog.target

[Service]
User=onesql
Type=forking
ExecStart=${DB_BASE_DIR}/bin/mysqld --defaults-file=${DB_CNF_FILE} --daemonize --user=onesql
ExecStop=${DB_BASE_DIR}/bin/mysqladmin -uroot -P${DB_PORT} -p${DB_PASS} -S ${DB_SOCKET} shutdown

[Install]
WantedBy=multi-user.target" >> ${DB_SERVICE_FILE_PATH}

    # 先停止手动启动服务
    func_stop_database
    # 服务列表重载
    systemctl daemon-reload
    # 重启onesql服务并开机自启
    systemctl start onesql
    systemctl enable onesql
    # 查看服务状态
    systemctl status onesql
    echo "**********************************Create OneSQL Service Finished"
}

# ---------核心逻辑按顺序执行--------
func_check_instance
func_stop_database
func_user
func_mkdir
func_create_mysql_config
func_init_database
func_start_database
func_check_instance
func_create_db_user
func_set_env
func_create_systemd_file_and_restart
echo "***************** end *****************"
echo "please enter \"source ~/.bash_profile\" to complete."
echo "***************** end *****************"


